package com.blacktry.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blacktry.utils.log.JobSchedule;
import com.blacktry.entity.schedule.ScheduleJob;
import com.blacktry.entity.schedule.ScheduleLog;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @calssName JobService
 * @Description
 * @Author blackTry
 */
@Service
public class JobService {
     //日志
    private static final Logger logger = LoggerFactory.getLogger(JobService.class);

    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private ScheduleLogService scheduleLogService;

    /**
     * 添加定时任务
     */
    public ScheduleJob addJob(ScheduleJob scheduleJob){
        scheduleJobService.save(scheduleJob);
        return scheduleJob;
    }

    /**
     * 查看所有任务列表
     */
    public Map<String,Object> getAllJob(){
        List<ScheduleJob> list = scheduleJobService.list();
        Map<String,Object> result = new HashMap<>();
        result.put("list", list);
        return result;
    }


    /**
     * 查看某个任务的执行详情
     */
    public Map<String,Object> getJobScheduleDetail(int jobId){
        QueryWrapper<ScheduleLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ScheduleLog::getId,jobId);
        List<ScheduleLog> list = scheduleLogService.list(queryWrapper);
        Map<String,Object> result = new HashMap<>();
        result.put("list", list);
        return result;
    }

    /**
     * 查看某个任务的详情
     */
    public Map<String,Object> getJobDetail(int jobId){
        ScheduleJob scheduleJob = scheduleJobService.getById(jobId);
        Map<String,Object> result = new HashMap<>();
        result.put("scheduleJob", scheduleJob);
        return result;
    }

    /**
     * 修改任务
     */
    public Map<String,Object> updateJob(ScheduleJob scheduleJob) throws Exception {
        Map<String,Object> result = new HashMap<>();

        Class<?> clszz = null;
        try {
            clszz = Class.forName(scheduleJob.getClazz());
        }catch (ClassNotFoundException e){
            logger.error("修改定时任务异常，无法找到指定的任务类");
            throw new Exception("无法找到指定的任务类");
        }
        
            Integer status = scheduleJob.getStatus();
            if(status == 1){ // 修改或者添加任务
                JobSchedule.modifyOrAddJobTime(scheduleJob.getName(), scheduleJob.getCron(),clszz);
            }else if(status == 2){ // 停止任务
                JobSchedule.removeJob(scheduleJob.getName());
            }

        scheduleJobService.updateById(scheduleJob);
        return result;
    }

    /**
     * 启动数据库中配置的定时任务
     */
    public void initScheduleJob() throws SchedulerException {
        //查询到所有的定时任务
        List<ScheduleJob> list = scheduleJobService.list();

        for (ScheduleJob scheduleJob: list){
            Class<?> clszz = null;
            try {
                clszz = Class.forName(scheduleJob.getClazz());
                JobSchedule.addJob(scheduleJob.getName(), clszz, scheduleJob.getCron(),scheduleJob.getStatus());
            } catch (ClassNotFoundException e){
                logger.error("初始化启动定时任务异常，无法找到指定的任务类");
                continue;
            }
        }
    }

    /**
     * 新增一条执行日志
     */
    public Integer saveScheduleLog(String name, int status, String logInfo){
        QueryWrapper<ScheduleJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ScheduleJob::getName,name);
        ScheduleJob scheduleJob = scheduleJobService.getOne(queryWrapper);
        ScheduleLog scheduleLog = new ScheduleLog(scheduleJob,status,logInfo);
        scheduleLogService.save(scheduleLog);
        return scheduleLog.getId();
    }

    /**
     * 更新一条执行日志
     */
    public void updateScheduleLog(String id, int status, String logInfo){
        QueryWrapper<ScheduleLog> queryWrapper = new QueryWrapper<>();
        ScheduleLog scheduleLog = new ScheduleLog();
        scheduleLog.setId(Integer.valueOf(id));
        scheduleLog.setStatus(status);
        scheduleLog.setLogInfo(logInfo);
        scheduleLogService.updateById(scheduleLog);
    }
}